<?php
namespace app\agent\logic;

use app\common\model\UserAgentModel;

class UserAgentLogic extends UserAgentModel
{
	
	public function getPage($where = [], $request = [])
	{
		//排序
		$order = [
				'status' => 'DESC',
				$this->getPk() => 'DESC',
		];

		//查询数据
		$data = $this->where($where)->order($order)->paginate(10, false, ['query' => $request]);

		//字段属性映射
		foreach ($data as $key => &$val)
		{
			$this->attributeMap($val);
		}
		
		return $data;
	}

	public function updateRecord($data = [])
	{
		//入库
		$data = $this->allowField(true)->save($data, [$this->getPk() => $data['id']]);
		
		if( $data === false )
		{
			return false;
		}
		
		return true;
	}
	
	public function destroyRecord($id = 0)
	{
		return $this->delete($id);
	}

	public function getDetail($where = [])
	{
		//查询数据
		$data = $this->where($where)->find();

		//字段属性映射
		$data = $this->attributeMap($data);

		return $data;
	}

    public function login($data)
    {
        $field = [
            'user.telephone', 'user.password', 'user.headimg', 'user.fullname', 'user.salt',
            'agent.*',
        ];

        $where = [
            ['user.telephone', '=', $data['username']],
        ];

        $join = [
            ['bg_user user', 'user.uid = agent.uid'],
        ];

        $user = $this->alias('agent')->field($field)->join($join)->where($where)->find();

        if( empty($user) )
        {
            $this->error = '账号不存在或不是代理商!';

            return false;
        }

        //验证密码
        if( bagmd5($data['password'], $user['salt']) !== $user['password'] )
        {
            $this->error = '账号或密码错误!';

            return false;
        }

        //是否合格
        if( $user['ishege'] === 2 )
        {
            $this->error = '该账号不合格!';

            return false;
        }

        //验证状态
        if( $user['status'] === 2 )
        {
            $this->error = '该账号已被冻结!';

            return false;
        }

        return $user;
	}

    public function freeLogin($uid)
    {
        $field = [
            'user.telephone', 'user.headimg', 'user.fullname',
            'agent.*',
        ];

        $where = [
            ['agent.uid', '=', $uid],
        ];

        $join = [
            ['bg_user user', 'user.uid = agent.uid'],
        ];

       return  $this->alias('agent')->field($field)->join($join)->where($where)->find();
	}
}